package com.insurance.interceptor;

import com.insurance.common.common.ResponseData;
import com.insurance.common.enums.CommonEnum;
import com.insurance.common.utils.JwtOperatorUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Style
 * @version 1.0
 * @date 2020/10/19
 **/
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        if(request.getRequestURI().contains("acceptForFee") || request.getRequestURI().contains("downLoadPDF") || request.getRequestURI().contains("printInvoice")){
            return true;
        }
        String token = request.getHeader("Authorization");
        System.out.println("【requestToken："+token+"】");
        if(JwtOperatorUtil.isTokenExpired(token)){
            response.getWriter().write(JSONObject.fromObject(ResponseData.error(CommonEnum.TOKEN_ERROR)).toString());
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        /*String token = request.getHeader("Authorization");
        log.info("【token: {}】", token);
        if(JwtOperatorUtil.isTokenExpired(token)){
            response.getWriter().write(JSONObject.fromObject(ResponseData.error(CommonEnum.TOKEN_ERROR)).toString());
        }*/
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
